package com.itheima.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.goods.dao.GoodsMapper;
import com.itheima.goods.pojo.Goods;
import com.itheima.goods.service.GoodsService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
    @Autowired
    GoodsMapper goodsMapper;

    @Override
    public PageResult findPage(Integer page, Integer size, Map<String, String> searchMap) {
        //条件分页查询
        LambdaQueryWrapper<Goods> wrapper = Wrappers.<Goods>lambdaQuery();
        if (searchMap.get("name") != null && searchMap.get("name").length() > 0) {
            wrapper.like(Goods::getName, searchMap.get("name"));
        }
        if (searchMap.get("brandName") != null && searchMap.get("brandName").length() > 0) {
            wrapper.eq(Goods::getBrandName, searchMap.get("brandName"));
        }
        if (searchMap.get("categoryName") != null && searchMap.get("categoryName").length() > 0) {
            wrapper.eq(Goods::getCategoryName, searchMap.get("categoryName"));
        }
        Page<Goods> goodsPage = page(new Page<Goods>(page, size), wrapper);
        PageResult<Goods> goodsPageResult = new PageResult<>();
        goodsPageResult.setTotal(goodsPage.getTotal());
        goodsPageResult.setRows(goodsPage.getRecords());
        return goodsPageResult;
    }

    @Override
    public Result buy(Long id, Integer buyNum) {

        //先查询id对应的商品
        Goods goods = goodsMapper.selectById(id);
        if (goods == null) {
            return new Result(false, StatusCode.ERROR, "商品不存在");
        }
        //判断商品库存是否够
        if (goods.getNum() < buyNum) {
            return new Result(false, StatusCode.ERROR, "商品库存不足");
        }
        //扣减商品库存
        goods.setNum(goods.getNum() - buyNum);
        //更新数据库
        goodsMapper.updateById(goods);
        return new Result(true, StatusCode.OK, "商品扣减成功");
    }

}
